use crate::models::brands::{self, CreateBrandParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;


pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/brands", post(create))
        .route("/brands/:id", get(get_by_id))
        .route("/brands/:id/delete", post(delete))
        .route("/brands/by-slug/:slug", get(get_by_slug))
        .route("/brands/by-name/:name", get(get_by_name))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateBrandParams>,
) -> Result<Response> {
    let brand = brands::Model::create(&state.db, &params).await?;
    format::json(brand)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let brand = brands::Model::find_by_id(&state.db, &id).await?;
    format::json(brand)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let brand = brands::Model::find_by_id(&state.db, &id).await?;
    brand.delete(&state.db).await?;
    format::json(())
}

async fn get_by_slug(
    State(state): State<AppContext>,
    axum::extract::Path(slug): axum::extract::Path<String>,
) -> Result<Response> {
    let brand = brands::Model::find_by_slug(&state.db, &slug).await?;
    format::json(brand)
}

async fn get_by_name(
    State(state): State<AppContext>,
    axum::extract::Path(name): axum::extract::Path<String>,
) -> Result<Response> {
    let brands = brands::Model::find_by_name(&state.db, &name).await?;
    format::json(brands)
}
